package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.lab.LabFinanceSettle;
import com.ysd.lis.entity.lab.LabFinanceSettleDetail;
import com.ysd.lis.entity.lab.LabFinanceSettlePayway;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.mapper.lab.LabFinanceSettleMapper;
import com.ysd.lis.mapper.lab.LabReqMainMapper;
import com.ysd.lis.request.lab.FinanceSettleDto;
import com.ysd.lis.request.lab.LabFinanceSettleDto;
import com.ysd.lis.request.lab.LabFinanceSettleVo;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.lab.LabFinanceSettleDetailService;
import com.ysd.lis.service.lab.LabFinanceSettlePaywayService;
import com.ysd.lis.service.lab.LabFinanceSettleService;
import com.ysd.lis.service.lab.LabReqMainService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 通道号管理表 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-10-29
 */
@Service
public class LabFinanceSettleServiceImpl extends ServiceImpl<LabFinanceSettleMapper, LabFinanceSettle> implements LabFinanceSettleService {
    @Autowired
    LabFinanceSettleMapper labFinanceSettleMapper;

    @Autowired
    LabFinanceSettleDetailService labFinanceSettleDetailService;
    @Autowired
    LabFinanceSettlePaywayService labFinanceSettlePaywayService;
    @Autowired
    LabReqMainService labReqMainService;
    @Autowired
    LabReqMainMapper labReqMainMapper;
    @Autowired
    private SysRuleSetService sysRuleSetService;

    @Override
    public Result findFinanceSettleList(FinanceSettleDto param) {

        MPJLambdaWrapper<LabFinanceSettle> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabFinanceSettle.class);
        if (ToolsUtils.isNotEmpty(param.getCompanyCode())) {
            queryWrapper.eq(LabFinanceSettle::getCompanyCode, param.getCompanyCode());
        }

        String settleDateBegin = param.getSettleDateBegin();
        if (ToolsUtils.isNotEmpty(settleDateBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                queryWrapper.ge(LabFinanceSettle::getSettleDate, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String settleDateEnd = param.getSettleDateEnd();
        if (ToolsUtils.isNotEmpty(settleDateEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                queryWrapper.le(LabFinanceSettle::getSettleDate, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(param.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(LabFinanceSettle::getSettleNo, param.getSearchValue())
                    .or().like(LabFinanceSettle::getCompanyName, param.getSearchValue()));
        }
        queryWrapper.eq(LabFinanceSettle::getDelFlag, 0);
        List<LabFinanceSettle> financeSettleList = labFinanceSettleMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", financeSettleList);

    }

    @Override
    public Result saveOrUpdateFinanceSettle(LabFinanceSettleDto labFinanceSettleDto) {
        if (CollectionUtils.isEmpty(labFinanceSettleDto.getSettleDetailList())) {
            return Result.fail("没有要保存的申请数据");
        }
        List<LabFinanceSettleDetail> labReqdetailList = labFinanceSettleDto.getSettleDetailList();
        //
        Double costs = labReqdetailList.stream().filter(x ->  Objects.nonNull(x.getBrokerageCosts())).mapToDouble(LabFinanceSettleDetail::getBrokerageCosts).sum();

        LabFinanceSettle labFinanceSettle = new LabFinanceSettle();
        if (StringUtils.isBlank(labFinanceSettleDto.getId())) {
            BeanUtil.copyProperties(labFinanceSettleDto, labFinanceSettle);
            String financeNo = sysRuleSetService.createRuleCodeList("financeNo", 1).get(0);
            labFinanceSettle.setSettleNo(financeNo);
            labFinanceSettle.setSettleDate(new Timestamp(System.currentTimeMillis()));
            labFinanceSettle.setBrokerageCosts(costs);
            //财务结账总表
            labFinanceSettleMapper.insert(labFinanceSettle);
        } else {
            BeanUtil.copyProperties(labFinanceSettleDto, labFinanceSettle);
            labFinanceSettle.setBrokerageCosts(costs);
            labFinanceSettleMapper.updateById(labFinanceSettle);
        }
        //删除申请,明细,支付方式
        labFinanceSettleDetailService.remove(new LambdaQueryWrapper<LabFinanceSettleDetail>().eq(LabFinanceSettleDetail::getSettleId, labFinanceSettle.getId()));
        labFinanceSettlePaywayService.remove(new LambdaQueryWrapper<LabFinanceSettlePayway>().eq(LabFinanceSettlePayway::getSettleId, labFinanceSettle.getId()));

        //获取reqNo集合批量修改LAB_REQMIAN 改为 已结算
        List<String> reqList =new ArrayList<>();
        for (LabFinanceSettleDetail labFinanceSettleDetail : labReqdetailList) {
            if (StringUtils.isNotBlank(labFinanceSettleDetail.getReqNo())){
                reqList.addAll(Arrays.asList(labFinanceSettleDetail.getReqNo().split(",")));
            }
        }
        //修改申请表为已结算
        labReqMainService.update(new LambdaUpdateWrapper<LabReqMain>().set(LabReqMain::getIsSettle, 1).in(LabReqMain::getReqNo, reqList).eq(LabReqMain::getDelFlag, 0));

        List<LabFinanceSettleDetail> financeSettleDetailList = new ArrayList<>();
        for (LabFinanceSettleDetail labFinanceSettleDetail : labReqdetailList) {
            labFinanceSettleDetail.setSettleId(labFinanceSettle.getId());
            labFinanceSettleDetail.setSettleNo(labFinanceSettle.getSettleNo());
            financeSettleDetailList.add(labFinanceSettleDetail);
        }
        labFinanceSettleDetailService.saveBatch(financeSettleDetailList);

        for (LabFinanceSettlePayway labFinanceSettlePayway : labFinanceSettleDto.getPayWayList()) {
            labFinanceSettlePayway.setSettleId(labFinanceSettle.getId());
            labFinanceSettlePayway.setSettleNo(labFinanceSettle.getSettleNo());
        }
        labFinanceSettlePaywayService.saveBatch(labFinanceSettleDto.getPayWayList());


        return Result.succ(1, "保存成功", labFinanceSettle);
    }

    @Override
    public Result chkFinanceSettle(LabFinanceSettle labFinanceSettle) {
        labFinanceSettle.setSettleDate(new Timestamp(System.currentTimeMillis()));
        int i = labFinanceSettleMapper.updateById(labFinanceSettle);
        if (i > 0) {
            return Result.succ(1, "审核成功！", null);
        } else {
            return Result.fail("审核失败！");
        }
    }

    @Override
    public Result findFinanceSettleById(LabFinanceSettle labFinanceSettle) {
        LabFinanceSettle financeSettle = labFinanceSettleMapper.selectById(labFinanceSettle.getId());
        LabFinanceSettleVo labFinanceSettleVo = new LabFinanceSettleVo();
        BeanUtil.copyProperties(financeSettle, labFinanceSettleVo);
        List<LabFinanceSettleDetail> detailList = labFinanceSettleDetailService.list(new LambdaQueryWrapper<LabFinanceSettleDetail>().eq(LabFinanceSettleDetail::getSettleId, financeSettle.getId()).eq(LabFinanceSettleDetail::getDelFlag, 0));
        labFinanceSettleVo.setDetailList(detailList);
        List<LabFinanceSettlePayway> paywayList = labFinanceSettlePaywayService.list(new LambdaQueryWrapper<LabFinanceSettlePayway>().eq(LabFinanceSettlePayway::getSettleId, financeSettle.getId()).eq(LabFinanceSettlePayway::getDelFlag, 0));
        labFinanceSettleVo.setPayWayList(paywayList);

        return Result.succ(1, "查询成功", labFinanceSettleVo);
    }

    @Override
    public Result batchDeleteFinanceSettleList(FinanceSettleDto dto) {
        List<LabFinanceSettle> labFinanceSettleList = dto.getLabFinanceSettleList();
        List<String> ids = labFinanceSettleList.stream().map(LabFinanceSettle::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if (b) {
            //DETAIL
            LambdaUpdateWrapper<LabFinanceSettleDetail> deleteTableWrapper = new LambdaUpdateWrapper<>();
            deleteTableWrapper.in(LabFinanceSettleDetail::getSettleId, ids);
            labFinanceSettleDetailService.remove(deleteTableWrapper);
            //PAYWAY
            LambdaUpdateWrapper<LabFinanceSettlePayway> deleteSelectWrapper = new LambdaUpdateWrapper<>();
            deleteSelectWrapper.in(LabFinanceSettlePayway::getSettleId, ids);
            labFinanceSettlePaywayService.remove(deleteSelectWrapper);
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result findReqMainBySettleList(FinanceSettleDto param) {
        //先根据ID查询明细
        MPJLambdaWrapper<LabFinanceSettleDetail> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabFinanceSettleDetail.class);
        queryWrapper.eq(LabFinanceSettleDetail::getDelFlag, 0);
        queryWrapper.eq(StringUtils.isNotBlank(param.getSettleId()),LabFinanceSettleDetail::getSettleId, param.getSettleId());
        if (ToolsUtils.isNotEmpty(param.getSettleNoes())) {
            String[] split = param.getSettleNoes().split(",");
            queryWrapper.in(LabFinanceSettleDetail::getSettleNo, Arrays.stream(split).collect(Collectors.toList()));
        }
        List<LabFinanceSettleDetail> settleReqList = labFinanceSettleDetailService.list(queryWrapper);
        List<String> collect = settleReqList.stream().map(LabFinanceSettleDetail::getReqNo).distinct().collect(Collectors.toList());
        HashSet set = new HashSet();
        for(String reqNos : collect){
            String[] split = reqNos.split(",");
            for(String s : split){
                set.add(s);
            }
        }
        MPJLambdaWrapper<LabReqMain> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMain.class);
        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);
        lambdaQueryWrapper.in(LabReqMain::getReqNo, set);
        List<LabReqMain> list = labReqMainMapper.selectList( lambdaQueryWrapper);

        return Result.succ(1, "查询成功", list);
    }

    @Override
    public Result findCompanyAndFinanceSettleList(FinanceSettleDto param) {
        MPJLambdaWrapper<LabFinanceSettle> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabFinanceSettle.class);
        if (ToolsUtils.isNotEmpty(param.getSalesmanCode())) {
            queryWrapper.eq(LabFinanceSettle::getSalesmanCode, param.getSalesmanCode());
        }
        if (ToolsUtils.isNotEmpty(param.getSettleStatus())) {
            queryWrapper.eq(LabFinanceSettle::getSettleStatus, param.getSettleStatus());
        }

        String settleDateBegin = param.getSettleDateBegin();
        if (ToolsUtils.isNotEmpty(settleDateBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                queryWrapper.ge(LabFinanceSettle::getSettleDate, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String settleDateEnd = param.getSettleDateEnd();
        if (ToolsUtils.isNotEmpty(settleDateEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(settleDateEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                queryWrapper.le(LabFinanceSettle::getSettleDate, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(param.getSearchValue())) {
            queryWrapper.and(wrapper -> wrapper.like(LabFinanceSettle::getSettleNo, param.getSearchValue())
                    .or().like(LabFinanceSettle::getCompanyName, param.getSearchValue()));
        }
        queryWrapper.eq(LabFinanceSettle::getDelFlag, 0);
        List<LabFinanceSettle> financeSettleList = labFinanceSettleMapper.selectList(queryWrapper);
        Map<List<String>, List<LabFinanceSettle>> companyMap = financeSettleList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getCompanyCode(), s.getCompanyName())));
        List<Map<String,Object>> list = new ArrayList<>();
        for (List<String> companylist : companyMap.keySet()) {
            Map<String,Object> map = new HashMap();
            String companyCode =  companylist.get(0);
            String companyName =  companylist.get(1);
            List<LabFinanceSettle> labFinanceSettles = companyMap.get(companylist);
            map.put("companyCode",companyCode);
            map.put("companyName",companyName);
            map.put("financeSettleList",labFinanceSettles);
            list.add(map);
        }

        return Result.succ(1, "查询成功", list);
    }
}
